import React, { useState, useEffect } from 'react';
import { Button, Card, Spin, notification } from 'antd';
import 'antd/dist/reset.css'; // 引入 Ant Design 样式

function App() {
  const [imageSrc, setImageSrc] = useState(null);
  const [currentImageId, setCurrentImageId] = useState(1); // 初始图片 ID
  const [totalImages, setTotalImages] = useState(0); // 图片总数
  const [loading, setLoading] = useState(false); // 加载状态

  const fetchImage = (imageId) => {
    setLoading(true);
    fetch(`http://localhost:3000/image/${imageId}`)
      .then(response => response.blob())
      .then(blob => {
        const url = URL.createObjectURL(blob);
        setImageSrc(url);
        setLoading(false);
      })
      .catch(error => {
        console.error('Error fetching image:', error);
        setLoading(false);
      });
  };

  const fetchTotalImages = () => {
    fetch('http://localhost:3000/images/count')
      .then(response => response.json())
      .then(data => {
        setTotalImages(data.count);
      })
      .catch(error => {
        console.error('Error fetching total images:', error);
      });
  };

  useEffect(() => {
    fetchTotalImages(); // 获取图片总数
    fetchImage(currentImageId); // 组件加载时获取初始图片
  }, [currentImageId]);

  const handleNext = () => {
    if (currentImageId < totalImages) {
      setCurrentImageId(prevId => prevId + 1);
    }
  };

  const handlePrevious = () => {
    if (currentImageId > 1) {
      setCurrentImageId(prevId => prevId - 1);
    }
  };

  const handleDelete = () => {
    setLoading(true);
    fetch(`http://localhost:3000/image/${currentImageId}`, {
      method: 'DELETE'
    })
      .then(response => {
        if (response.ok) {
          notification.success({ message: 'Image deleted successfully!' });
          if (currentImageId > 1) {
            setCurrentImageId(prevId => prevId - 1); // 显示上一张图片
          } else {
            fetchImage(1); // 如果是第一张图片，则重新获取第一张图片
          }
          fetchTotalImages(); // 更新总图片数量
        } else {
          notification.error({ message: 'Failed to delete image.' });
        }
        setLoading(false);
      })
      .catch(error => {
        console.error('Error deleting image:', error);
        notification.error({ message: 'Failed to delete image.' });
        setLoading(false);
      });
  };

  return (
    <div style={{ padding: '20px' }}>
      <Card
        style={{ width: '100%', maxWidth: '600px', margin: '0 auto' }}
        cover={
          loading ? (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Spin size="large" />
            </div>
          ) : imageSrc ? (
            <img alt="Loaded" src={imageSrc} style={{ width: '100%' }} />
          ) : null
        }
      >
        <div style={{ textAlign: 'center' }}>
          <Button
            style={{ marginRight: '10px' }}
            type="primary"
            onClick={handlePrevious}
            disabled={loading || currentImageId <= 1}
          >
            Previous Image
          </Button>
          <Button
            style={{ marginRight: '10px' }}
            type="primary"
            onClick={handleNext}
            disabled={loading || currentImageId >= totalImages}
          >
            Next Image
          </Button>
          <Button
            type="danger"
            onClick={handleDelete}
            disabled={loading || !imageSrc}
          >
            Delete Image
          </Button>
        </div>
      </Card>
    </div>
  );
}

export default App;
